package cn.kmia.hrm.service.system;

import cn.kmia.hrm.pojo.system.Permission;
import cn.kmia.hrm.pojo.system.Role;
import cn.kmia.hrm.service.BaseService;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @项目：carms
 * @作者：4K
 * @描述：角色信息服务类
 * @日期：created in 16:45 2018/1/30
 */
@IocBean
public class RoleInfoService extends BaseService {

    private static final Log log = Logs.get();

    @Inject
    protected RolePermissionService rolePermissionService;

    /**
     * 分页查询
     *
     * @param name
     * @param pager
     * @return
     */
    public QueryResult queryByPage(String name, Pager pager) {
        Cnd cnd = Cnd.where("1", "=", 1);
        if (!Strings.isBlank(name) && !"null".equals(name)) {
            cnd.and("name", "like", "%" + name + "%");
        }
        cnd.and("delFlag", "is", null);
        List<Role> list = dao.queryByJoin(Role.class, "permissions", cnd, pager);
        List<Role> rtList = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            List<Permission> perList;
            String perNames;
            for (Role role : list) {
                perNames = "";
                perList = role.getPermissions();
                if (perList != null) {
                    for (Permission per : perList) {
                        perNames += per.getDescription() + ",";
                    }
                }
                role.setPerNames(perNames);
                rtList.add(role);
            }
        }
        QueryResult qr = new QueryResult();
        qr.setList(rtList);
        pager.setRecordCount(dao.count(Role.class, cnd));
        qr.setPager(pager);
        return qr;
    }

    /**
     * 查询
     *
     * @return
     */
    public List<Role> query() {
        return dao.query(Role.class, Cnd.where("delFlag", "is", null));
    }

    /**
     * 新增
     *
     * @param role        角色信息
     * @param user_idcard 操作人
     * @return
     */
    public Role add(Role role, String user_idcard) {
        if (checkRole(role.getName())) {
            return null;
        }
        role.setOpBy(user_idcard);
        role.setCreateTime(new Timestamp(new Date().getTime()));
        role.setUpdateTime(new Timestamp(new Date().getTime()));
        role = dao.insert(role);
        return role;
    }

    /**
     * 更新
     *
     * @param role        角色信息
     * @param user_idcard 操作人
     * @return
     */
    public boolean update(Role role, String user_idcard) {
        role.setOpBy(user_idcard);
        role.setUpdateTime(new Timestamp(new Date().getTime()));
        return dao.updateIgnoreNull(role) > 0 ? true : false;
    }

    /**
     * 删除用户，实际标记用户delFlag为true
     *
     * @param ids
     * @return
     */
    @Aop(TransAop.READ_COMMITTED)
    public NutMap del(int[] ids) throws Exception {
        NutMap nm = new NutMap();
        if (ids != null && ids.length > 0) {
            dao.update(Role.class, Chain.make("delFlag", true), Cnd.where("id", "in", ids));
            // 删除角色权限
            String idsStr = Arrays.toString(ids).substring(1,Arrays.toString(ids).length()-1);
            rolePermissionService.delete(idsStr);
            nm.setv("success", true);
        } else {
            nm.setv("success", false).setv("errorMsg", "请重试！");
        }
        return nm;
    }

    /**
     * 查询角色名称是否存在
     *
     * @param roleName
     * @return 存在 true,不存在 false
     */
    public boolean checkRole(String roleName) {
        int count = dao.count(Role.class, Cnd.where("name", "=", roleName));
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取角色
     *
     * @param id
     * @return
     */
    public Role getRole(int id) {
        return dao.fetch(Role.class, Cnd.where("id", "=", id));
    }
}
